package com.stp.rabbitmq.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.crypto.digest.MD5;
import com.stp.rabbitmq.config.ShardingFileConfig;
import com.stp.rabbitmq.entity.MessageEntity;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.Arrays;

@RestController
@RequestMapping("/file")
public class FileRabbitmqController {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/sendMsg61")
    public String sendMsg() {
        // 准备分片参数信息
        // 待传输文件
        File file = new File("C:\\Users\\mingming\\Downloads\\1云平台一站式部署.mp4");
        // 文件UUID，组装文件分片的唯一标识
        String uuid = UUID.fastUUID().toString();
        // 文件名
        String filename = file.getName();
        // 文件md5码
        String identifier = MD5.create().digestHex(file);
        // 默认切片大小：1M
        int chunkSize = 1024 * 1024;
        // 文件总大小
        int totalSize = (int) file.length();
        // 文件切片总数
        int totalChunks = totalSize % chunkSize == 0 ? totalSize / chunkSize : (totalSize / chunkSize + 1);
        // 文件字节数组
        byte[] fileContent = FileUtil.readBytes(file);

        for (int i = 1; i <= totalChunks; i++) {
            byte[] body;
            if (i == totalChunks) {
                // 最后一块
                body = Arrays.copyOfRange(fileContent, chunkSize * (i - 1), totalSize);
            } else {
                body = Arrays.copyOfRange(fileContent, chunkSize * (i - 1), chunkSize * i);
            }

            // 当前是第几片（切片）
            int chunkNumber = i;

            // 当前切片大小
            long currentChunkSize = body.length;

            // 组装发送数据
            MessageEntity message = new MessageEntity();
            message.setBody(body);
            message.setFilename(filename);
            message.setIdentifier(identifier);
            message.setUuid(uuid);
            message.setChunkNumber(chunkNumber);
            message.setChunkSize(chunkSize);
            message.setCurrentChunkSize(currentChunkSize);
            message.setTotalChunks(totalChunks);
            message.setTotalSize(totalSize);

            // 发送数据
            rabbitTemplate.convertAndSend("", ShardingFileConfig.SHARDING_FILE_QUEUE, Convert.toPrimitiveByteArray(message));
        }

        return "发送成功";
    }
}
